<template>
  <el-breadcrumb class="app-breadcrumb" separator-class="el-icon-arrow-right">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="item.path">
        <span v-if="item.children?.length || index === breadcrumbs.length - 1" class="no-redirect">
          {{ item.meta.title }}
        </span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, reactive, toRefs, watch } from 'vue'
import { useRoute, useRouter, RouteLocationMatched } from 'vue-router'
import { compile } from 'path-to-regexp'

export default defineComponent({
  setup() {
    const route = useRoute()
    const router = useRouter()

    const pathCompile = (path: string) => {
      const { params } = route
      const toPath = compile(path)
      return toPath(params)
    }

    const state = reactive({
      breadcrumbs: [] as Array<RouteLocationMatched>,
      getBreadcrumb: () => {
        let matched = route.matched.filter((item) => item.meta && item.meta.title)
        console.log(matched)
        const frist = matched[0]
        if (!state.isDashboard(frist)) {
          matched = [{ path: '/dashboard', meta: { title: '首页' } } as any].concat(matched)
        }
        state.breadcrumbs = matched.filter((item) => {
          return item.meta?.title && item.meta.breadcrumb !== false
        })
      },
      isDashboard(route: RouteLocationMatched) {
        return route?.name === 'Dashboard'
      },
      handleLink(item: any) {
        const { redirect, path } = item
        if (redirect) {
          router.push(redirect)
          return
        }
        router.push(pathCompile(path))
      }
    })

    watch(
      () => route.path,
      (path) => {
        if (path.startsWith('/redirect/')) {
          return
        }
        state.getBreadcrumb()
      }
    )

    onBeforeMount(() => {
      state.getBreadcrumb()
    })

    return {
      ...toRefs(state)
    }
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/vars.scss';

.el-breadcrumb__inner,
.el-breadcrumb__inner a {
  font-weight: 400 !important;
}

.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: $color-text-secondary;
    cursor: text;
  }
}
</style>
